<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    const state = reactive({
      map: ref(null),
      mapBox: ref(null),
      Txt: ref(null),
      tool: 'LineString', // 当前选中的工具
      tools: [ // 工具集
        {
          value: 'LineString',
          label: '线条'
        },
        {
          value: 'Polygon',
          label: '多边形'
        },
        {
          value: 'Circle',
          label: '圆'
        },
        {
          value: 'None',
          label: '无'
        }
      ],
      draw: null,
      source: new VectorSource({
        wrapX: false // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
      }),
      raster: new Tile({
        source: new XYZ({
          url: 'https://api.maptiler.com/maps/basic-4326/256/{z}/{x}/{y}.png?key=B3EG5uYPUvFucEWVoCa3',
          crossOrigin: ''
        })
      }),
      modify: null
    })

    // 监听绘制的类型
    watch(() => state.tool, () => {
      addInteraction()
    })

    const init = () => {
      const vector = new VectorLayer({
        source: state.source,
        style: new Style({
          fill: new Fill({
            color: 'rgba(220, 85, 255, 0.6)'
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: '#ffcc33'
            })
          })
        })
      })

      state.map = new Map({
        target: state.mapBox,
        layers: [state.raster, vector],
        view: new View({
          center: [0, 0],
          zoom: 3
        })
      })

      addInteraction()
    }

    // 开始绘制
    const addInteraction = () => {
      if (state.draw !== null) {
        state.map.removeInteraction(state.draw)
      }
      if (state.tool !== 'None') {
        state.draw = new Draw({
          source: state.source,
          type: state.tool,
          freehand: true
        })
        state.map.addInteraction(state.draw)
      }
    }
    `
    return {
      code
    }
  }
}
</script>
